package org.changs.record.video;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import org.changs.aplug.base.BaseActivity;
import org.changs.media.MediaFile;
import org.changs.media.MediaManager;
import org.changs.record.R;
import org.changs.record.databinding.VideoPlayActBinding;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;

/**
 * 视频播放
 * Created by Administrator on 2017/8/24.
 */


public class VideoPlayAct extends BaseActivity {

    public static final String TAG_MEDIA_FILE = "tag_media_file";
    public static final String ACTION_DELETE_MEDIA_FILE = "org.changs.record.video.ACTION_DELETE_MEDIA_FILE";

    private VideoPlayActBinding mBinding;
    private Disposable disposable;
    private MyMediaController myMediaController;
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    private MediaFile mMediaFile;
    @Inject
    MediaManager mMediaManager;


    public static void start(Context context, MediaFile mediaFile) {
        Intent starter = new Intent(context, VideoPlayAct.class);
        starter.putExtra(TAG_MEDIA_FILE, mediaFile);
        context.startActivity(starter);
    }

    @Override
    public void setup(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Vitamio.isInitialized(getContext());
        mBinding = DataBindingUtil.setContentView(this, R.layout.video_play_act);

        initData(savedInstanceState);
    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mMediaFile = savedInstanceState.getParcelable(TAG_MEDIA_FILE);
        } else {
            mMediaFile = getIntent().getParcelableExtra(TAG_MEDIA_FILE);
        }
        if (mMediaFile == null) {
            finish();
            return;
        }

        //设置播放地址
//        mBinding.videoView.setVideoURI(Uri.parse("http://112.253.22.157/17/z/z/y/u/zzyuasjwufnqerzvyxgkuigrkcatxr/hc.yinyuetai.com/D046015255134077DDB3ACA0D7E68D45.flv"));
        mBinding.videoView.setVideoPath(mMediaFile.getAbsolutePath());
        //创建控制器
        myMediaController = new MyMediaController(this, mBinding.videoView, this);
        myMediaController.setLockListener(isLock -> {
            if (isLock) mMediaManager.lock(mMediaFile);
            else mMediaManager.unLock(mMediaFile);
        });
        myMediaController.setLock(mMediaFile.isLock());
        //设置控制器
        mBinding.videoView.setMediaController(myMediaController);

        //设置高画质
        mBinding.videoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
        mBinding.videoView.requestFocus();

        countTime();

        mBinding.videoView.setOnPreparedListener(mp -> {
            //设置显示时长5s后隐藏
            myMediaController.show(5000);
        });
        myMediaController.setOnDeleteListener(() -> showDialog());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(TAG_MEDIA_FILE, mMediaFile);
    }

    //系统当前时间
    private void countTime() {
        disposable = Observable.interval(1, TimeUnit.SECONDS)
                .compose(this.bindUntilDestroy(true))
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    String str = sdf.format(new Date());
                    myMediaController.setTime(str);
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null)
            disposable.dispose();
        if (dialog != null)
            dialog = null;
    }

    private AlertDialog dialog;

    private void showDialog() {
        if (dialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_delete, null);
            dialog = new AlertDialog.Builder(this).setView(view).create();
            TextView textView = (TextView) view.findViewById(R.id.tv_content);
            if (mMediaFile.isLock()) {//视频被锁定
                textView.setText("该视频已被您锁定，确定删除吗？");
            } else {
                textView.setText("确定删除该视频吗？");
            }
            view.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
            view.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(ACTION_DELETE_MEDIA_FILE);
                intent.putExtra(TAG_MEDIA_FILE, mMediaFile);
                sendBroadcast(intent);//为什么这里用广播，因为该activity和其他activity不在同一进程。无法共享对象
            });
        }
        dialog.show();
    }
}
